package com.cdgeekcamp.redas.recr_page_worker.component;

import com.cdgeekcamp.redas.db.model.Position;
import com.cdgeekcamp.redas.db.model.PositionRepository;
import com.cdgeekcamp.redas.db.model.R_PositionCompanyEmployee;
import com.cdgeekcamp.redas.db.model.R_PositionCompanyEmployeeRepository;
import com.cdgeekcamp.redas.lib.core.RecrPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class PositionBuildServiceImpl implements RecrPageBuildService {
    @Autowired
    private PositionRepository positions;

    @Autowired
    private R_PositionCompanyEmployeeRepository r_positionCompanyEmployees;

    public Integer build(RecrPage recrPage, Integer... relatedIds) {
        String srcName = recrPage.getSrcName();
        String srcPosId = recrPage.getSrcPosId();
        String srcUrl = recrPage.getSrcUrl();
        String positionEdu = recrPage.getEdu();
        String positionExp = recrPage.getExp();
        String positionLocation = recrPage.getLocation();
        String positionSalary = recrPage.getSalary();
        String positionDescribe = recrPage.getPosDesc();
        String positionPosition = recrPage.getPosition();
        String positionPublishTime = recrPage.getPublishTime();

        Optional<Position> positionOpt = positions.findBySrcNameAndSrcPosId(srcName, srcPosId);
        Position position;

        if (positionOpt.isEmpty()) {
            position = positions.save(
                    new Position(srcName, srcPosId, srcUrl, positionEdu, positionExp, positionLocation,
                            positionSalary, positionDescribe, positionPosition, positionPublishTime)
            );
            log.info(String.format("职位发布平台：%s，发布平台职位编号：%s不存在，新建中......", srcName, srcPosId));
        } else {
            position = positionOpt.get();
            log.info(String.format("职位发布平台：%s，发布平台职位编号：%s 已经存在......", srcName, srcPosId));
        }

        Integer companyId = relatedIds[0];
        Integer employeeId = relatedIds[1];
        Integer positionId = position.getId();

        Optional<R_PositionCompanyEmployee> r_positionCompanyEmployeeOpt =
                r_positionCompanyEmployees.findByEmployeeIdAndCompanyIdAndPositionId(employeeId, companyId, positionId);

        if (r_positionCompanyEmployeeOpt.isEmpty()) {
            r_positionCompanyEmployees.save(new R_PositionCompanyEmployee(employeeId, companyId, positionId));
            log.info(
                    String.format(
                            "雇员：%s->公司：%s->职位：%s关联不存在，新建中......", employeeId, companyId, positionId)
            );
        } else
            log.info(
                    String.format("雇员：%s->公司：%s->职位：%s 关联已经存在......", employeeId, companyId, positionId)
            );

        return positionId;
    }
}
